'use client'

import { useEffect, useCallback } from 'react'
import { useRouter, usePathname, useSearchParams } from 'next/navigation'
import { useUIStore } from '@/stores/uiStore'

export function useNavigation() {
    const router = useRouter()
    const pathname = usePathname()
    const searchParams = useSearchParams()
    const { navigation, navigate, updateBreadcrumbs } = useUIStore()

    // 监听路径变化并更新导航状态
    useEffect(() => {
        const fullPath = pathname + (searchParams.toString() ? `?${searchParams.toString()}` : '')
        if (fullPath !== navigation.currentPath) {
            navigate(fullPath)
        }
    }, [pathname, searchParams, navigation.currentPath, navigate])

    // 导航到指定路径并保存状态
    const navigateTo = useCallback((path: string, state?: Record<string, unknown>) => {
        // 保存当前页面状态到sessionStorage
        if (typeof window !== 'undefined') {
            const currentState = {
                path: navigation.currentPath,
                timestamp: Date.now(),
                state: state || {}
            }
            sessionStorage.setItem(`nav_state_${navigation.currentPath}`, JSON.stringify(currentState))
        }

        navigate(path, state)
        router.push(path)
    }, [navigation.currentPath, navigate, router])

    // 返回上一页并恢复状态
    const goBack = useCallback(() => {
        if (navigation.canGoBack && navigation.history.length > 0) {
            const previousEntry = navigation.history[navigation.history.length - 1]

            // 尝试恢复页面状态
            if (typeof window !== 'undefined') {
                const savedState = sessionStorage.getItem(`nav_state_${previousEntry.path}`)
                if (savedState) {
                    try {
                        const parsedState = JSON.parse(savedState)
                        // 这里可以根据需要恢复特定的状态
                        console.log('Restoring state:', parsedState)
                    } catch (error) {
                        console.warn('Failed to parse saved navigation state:', error)
                    }
                }
            }

            router.push(previousEntry.path)
        } else {
            router.back()
        }
    }, [navigation.canGoBack, navigation.history, router])

    // 返回首页
    const goHome = useCallback(() => {
        navigateTo('/')
    }, [navigateTo])

    // 快速导航到数据集页面
    const goToDataset = useCallback((datasetId: string) => {
        navigateTo(`/dataset/${datasetId}`)
    }, [navigateTo])

    // 快速导航到任务页面
    const goToTask = useCallback((datasetId: string, taskId: string) => {
        navigateTo(`/task/${datasetId}/${taskId}`)
    }, [navigateTo])

    // 清除导航历史
    const clearHistory = useCallback(() => {
        if (typeof window !== 'undefined') {
            // 清除所有保存的导航状态
            Object.keys(sessionStorage).forEach(key => {
                if (key.startsWith('nav_state_')) {
                    sessionStorage.removeItem(key)
                }
            })
        }
    }, [])

    // 保存当前页面状态
    const saveCurrentState = useCallback((state: Record<string, unknown>) => {
        if (typeof window !== 'undefined') {
            const currentState = {
                path: navigation.currentPath,
                timestamp: Date.now(),
                state
            }
            sessionStorage.setItem(`nav_state_${navigation.currentPath}`, JSON.stringify(currentState))
        }
    }, [navigation.currentPath])

    // 获取保存的页面状态
    const getSavedState = useCallback((path?: string): Record<string, unknown> | null => {
        if (typeof window !== 'undefined') {
            const targetPath = path || navigation.currentPath
            const savedState = sessionStorage.getItem(`nav_state_${targetPath}`)
            if (savedState) {
                try {
                    return JSON.parse(savedState).state
                } catch (error) {
                    console.warn('Failed to parse saved state:', error)
                }
            }
        }
        return null
    }, [navigation.currentPath])

    return {
        // 状态
        currentPath: navigation.currentPath,
        canGoBack: navigation.canGoBack,
        canGoForward: navigation.canGoForward,
        breadcrumbs: navigation.breadcrumbs,
        history: navigation.history,

        // 方法
        navigateTo,
        goBack,
        goHome,
        goToDataset,
        goToTask,
        updateBreadcrumbs,
        clearHistory,
        saveCurrentState,
        getSavedState
    }
}